const api = require("../../../../utils/apiUtils");
const app = getApp();

Page({
  data: {
    money:0,        //账户余额

    deviceSn:'',    //设备序列号
    slotNum:0,      //选择的充电口
    deviceInfo:{},  //设备信息

    menuIndex:0,    //选中的额度下标
    menuValue:0,    //选中的额度值
    menuCustom:0,   //自定义额度值
    menuList:['0'], //额度列表

    isShowCostRatio:false, //是否展示费率
    checked:true,   //阅读用户协议
    modalName:null,
  },
  _init(options){
    let self = this;
    let deviceInfo = app.globalData.deviceInfo;
    if(deviceInfo&&(deviceInfo.deviceSn!=options.deviceSn)){
        deviceInfo = null;
    }
    if(!deviceInfo){
      my.showLoading({
        title: '加载中...',
      })
      //api-获取设备信息
      api.post(api.url.cdczScan,{
        deviceSn:options.deviceSn
      },(res)=>{
        my.hideLoading();
        console.log(res.data)
        if(res.data.code==200){
          my.hideLoading();
          //若设备离线\饱和，则使用返回首页
          if(res.data.body.state!=1){
            let msg = (res.data.body.state==2)?"设备离线":"设备饱和"
            msg += ",请使用其他设备";
            my.showModal({
                content: msg,
                showCancel:false,
                complete: () => {
                    self.toIndex();
                }
            })
            return;
          }
          deviceInfo = res.data.body;
          app.globalData.deviceInfo = deviceInfo;
          self._handleDeviceInfo(deviceInfo);
        }else{
          my.hideLoading();
          my.showModal({
            content: '未获取设备状态，请稍后再试！',
            showCancel:false,
            complete: () => {
                self.toIndex();
            }
          })
        }
      })
    }else{
        this._handleDeviceInfo(deviceInfo)
    }
    //获取账户余额
    api.post(api.url.walletGet,{
        memberId:app.globalData.userInfo.memberId
    },(res)=>{
        if(res.data.code==200){
          self.setData({
            money:res.data.body.money
          })
        }
    })
},
//支付充电
_payHandel(times,callBacl){
    let self = this;
    api.post(api.url.cdczpay,{
      deviceSn:self.data.deviceSn,
      slotNum:self.data.slotNum,
      timesMinute:times
    },(res)=>{
      console.log(res)
      if(res.data.code==200){
        const tradeNo = res.data.body.tradeNo;
        self.toUnderway(tradeNo);
      }else{
        my.showModal({
          title: '支付失败',
          content: res.data.msg,
          showCancel:false,
          complete: () => {
            my.reLaunch({
              url: '/pages/newIndex/index',
            })
          }
        })
      }
      if(callBacl){
        return callBacl();
      }
    })
},
_handleDeviceInfo(deviceInfo){
    const meterCost = deviceInfo.electricityMeterCost;
    if(deviceInfo.pimItems){
        for (let index = 0; index < deviceInfo.pimItems.length; index++) {
            const element = deviceInfo.pimItems[index];
            element['money'] = parseFloat(element.moneyStr);
        }
    }
    let menuArr = [];
    if(meterCost){
        if(meterCost.maxChargeTimesMinute>0){
            //如果时间套餐为0代表充满即停
            menuArr.push('0');
        }
        
        if(deviceInfo.timeSetMealList){
            menuArr = menuArr.concat(deviceInfo.timeSetMealList)
        }
        menuArr.push('-1');
        this.setData({
            menuList:menuArr,
            deviceInfo:deviceInfo,
        })
    }
    
},
btnShowModal(e){
    this.setData({modalName:e.currentTarget.dataset.modal})
},
btnHideModal(){
    this.setData({modalName:null})
},
btnPay(){
    console.log("点击支付")
    my.showLoading({
      title: '"支付中..."',
    })
    const times = this.data.menuValue; //选中套餐
    const self = this;
    if(times<0){
        my.hideLoading();
        my.showModal({
          title: '温馨提示',
          content: '请输入大于零整数时间',
          showCancel:false
        })
    }else{
        if(this.data.deviceInfo.electricityMeterCost.walletState==2){
            //余额不足
            my.hideLoading();
            my.showModal({
              title: '温馨提示',
              content: '余额不足，请前往充值！',
              confirmText:'账户充值',
              cancelText:'稍后再说',
              complete: (res) => {
                if (res.confirm) {
                  self.toWallet();
                }
              }
            })
            return;
        }else{
            this._payHandel(times * 60,()=>{
                my.hideLoading();
            })
        }
    }
},
//按钮点击继续充电
btnPayHandel(){
    this.setData({
        modalName:null
    })
    my.showLoading({
      title: '设备开启中...',
      mask:true
    })
    const times = this.data.menuValue; //获取选中套餐值
    this._payHandel(times*60,()=>{
        my.hideLoading();
    })
},
//自定义input输入框输入
btnInput(e){
    const val = parseInt(e.detail.value)||0;
    this.setData({
        menuValue:val,
        menuCustom:val,
    })
},
//切换选中菜单项
btnChangeMenu(e){
    const index = e.currentTarget.dataset.index;
    this.setData({
        menuIndex:index,
        menuValue:parseInt(this.data.menuList[index])
    })
},
//切换费率展示
btnChangeCost(){
    this.setData({
        isShowCostRatio:!this.data.isShowCostRatio
    })
},
//切换已读状态
btnChangeRead(){
    this.setData({
        checked:!this.data.checked
    })
},
//////////////页面跳转
toBack(){
    my.navigateBack()
},
toWallet(){
    const {deviceSn,slotNum} = this.data;   
    my.redirectTo({
        url:`/pages/wallet/index/index?deviceSn=${deviceSn}&slot=${slotNum}`
    })
},
toIndex(){
    my.reLaunch({
        url: '/pages/index/index',
    })
},
toUnderway(tradeNo){
    if(!tradeNo) return;
    my.reLaunch({
      url:"../underway/underway?tradeNo="+tradeNo,
    })
},
  onLoad(options) {
    console.log(options)
    if(options.deviceSn){
      this.setData({
        deviceSn:options.deviceSn,
        slotNum:options.num
      })
    }
    this._init(options);
  },
});
